package com.xisoft.bx.service.billService;

import com.alibaba.fastjson.JSONObject;
import com.xisoft.core.common.strhelp.StringHelp;
import com.xisoft.core.common.util.JsonMap;
import com.xisoft.action.SuperAction;
import com.xisoft.utils.PubConvert;
import com.xisoft.security.CurrentUser;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author xzh
 * @Date 2022/9/6 11:17
 * @Description
 * @Version 1.0
 **/
@Log4j2
@Service("BillServiceImpl")
public class BillServiceImpl extends SuperAction {

    public static ConcurrentHashMap<String, Object> hashCache = new ConcurrentHashMap<>();

    /**
     * @param areaId
     * @return
     * @throws Exception
     */
    public String getAreaName(String areaId) throws Exception {
        String area_name = "";
        String cache_areaName = PubConvert.ToString(hashCache.get("area_" + areaId));
        if (StringUtils.isNotEmpty(cache_areaName)) {
            return cache_areaName;
        }
        if (StringUtils.isNotEmpty(areaId)) {
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("id", areaId);
            List<Map<String, Object>> list = (List<Map<String, Object>>) configDao.executeConfig("queryAreaName", valMap);
            if (CollectionUtils.isNotEmpty(list)) {
                area_name = PubConvert.ToString(list.get(0).get("value"));
                hashCache.put("area_" + areaId, area_name);
            }
        }
        return area_name;
    }

    /**
     * 每个人员对应的科室职务信息
     *
     * @param emp_ids
     * @param companyID
     * @return
     */
    public Map<String, List<Map<String, Object>>> getOrgsAll(String emp_ids, String companyID) {
        List<Map<String, String>> jobMaps = queryKSAndZWfromBD(emp_ids, companyID);
        Map<String, List<Map<String, String>>> groupEmpOrgs = groupByBheId(jobMaps);
        List positionList = new ArrayList();
        List jobsList = new ArrayList();
        for (Map<String, String> temp : jobMaps) {
            if (StringUtils.isNotBlank(temp.get("jobs_in_dept"))) {
                jobsList.add(temp.get("jobs_in_dept"));
            }
            if (StringUtils.isNotBlank(temp.get("jobs_position_title"))) {
                positionList.add(temp.get("jobs_position_title"));
            }
        }
        if (CollectionUtils.isNotEmpty(jobsList)) {
            List<Map<String, String>> orgDataMaps = queryOrgListForSelect(String.join(",", jobsList));
            List<Map<String, String>> positions = jobsPosttionSelect(positionList);
            Map<String, List<Map<String, Object>>> groupOrgs = getGroupOrgList(groupEmpOrgs,
                    orgDataMaps, positions);
            return groupOrgs;
        }
        return new HashMap<>();
    }

    /**
     * ===================================
     * 查询人员科室职务
     *
     * @param empIds
     * @param companyId
     * @return
     */
    public List<Map<String, String>> queryKSAndZWfromBD(String empIds, String companyId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("emp_ids", empIds);
        map.put("company_id", companyId);
        List<Map<String, String>> resultList = (List<Map<String, String>>) configDao.executeConfig("queryKSAndZWfromBD", map);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 根据每个人员进行分组
     *
     * @param jobMaps
     * @return
     */
    public Map<String, List<Map<String, String>>> groupByBheId(List<Map<String, String>> jobMaps) {
        Map<String, List<Map<String, String>>> map = new HashMap<>();
        for (Map<String, String> temp : jobMaps) {
            String bheId = temp.get("bhe_id");
            if (CollectionUtils.isEmpty(map.get(bheId))) {
                map.put(bheId, new ArrayList<Map<String, String>>());
            }
            map.get(bheId).add(temp);
        }
        return map;
    }

    /**
     * 获取每个人对应的科室职务信息
     *
     * @param groupEmpOrgs
     * @param orgDataMaps
     * @param positions
     * @return
     */
    public Map<String, List<Map<String, Object>>> getGroupOrgList(Map<String, List<Map<String, String>>> groupEmpOrgs, List<Map<String, String>> orgDataMaps, List<Map<String, String>> positions) {
        Map<String, List<Map<String, Object>>> result = new HashMap<>();

        //根据oid 分组
        Map<String, List<Map<String, String>>> orgDataMapsForOid = orgDataMaps.stream().collect(Collectors.groupingBy(
                e -> e.get("oid").toString()));
        Map<String, List<Map<String, String>>> positionForCode = positions.stream().collect(Collectors.groupingBy(
                e -> e.get("code").toString()));
        for (Map.Entry<String, List<Map<String, String>>> entry : groupEmpOrgs.entrySet()) {
            // 每个人的 科室 职位信息
            List<Map<String, Object>> resultItem = new ArrayList<>();
            List<Map<String, String>> empOrgs = entry.getValue();
            for (Map<String, String> empOrgItem : empOrgs) {
                String jobsPositionTitle = empOrgItem.get("jobs_position_title");
                List<Map<String, String>> jobsPosition = positionForCode.get(jobsPositionTitle);
                List<Map<String, String>> jobsInDept = orgDataMapsForOid.get(empOrgItem.get(
                        "jobs_in_dept"));
                Map<String, Object> item = new HashMap<>();
                if (CollectionUtils.isNotEmpty(jobsInDept)) {
                    item.put("value", jobsInDept.get(0).get("oid"));
                    item.put("text", jobsInDept.get(0).get("oname"));
                }
                if (CollectionUtils.isNotEmpty(jobsInDept)) {
                    item.put("position", jobsPosition.get(0).get("value"));
                }
                resultItem.add(item);
            }
            result.put(entry.getKey(), resultItem);
        }
        return result;
    }

    /**
     * 获取当前用户的科室职务信息
     *
     * @param groupOrgs
     * @param userId
     * @param bheId
     * @return
     */
    public List<Map<String, Object>> getOrgs(Map<String, List<Map<String, Object>>> groupOrgs, String userId, String bheId) {
        List<Map<String, Object>> orgs = new ArrayList<>();
        if (StringUtils.isNotBlank(userId)) {
            orgs = groupOrgs.get(userId);
        } else {
            orgs = groupOrgs.get(bheId);
        }
        if (CollectionUtils.isEmpty(orgs)) {
            orgs = groupOrgs.get(bheId);
        }
        return orgs;
    }

    /**
     * 查询科室数据列表
     *
     * @param orgList
     * @return
     */
    public List<Map<String, String>> queryOrgListForSelect(String orgList) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("org_list", orgList);
        List<Map<String, String>> resultList = (List<Map<String, String>>) configDao.executeConfig("queryOrgListForSelect", map);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 职务下拉
     *
     * @param codeList
     * @return
     */
    public List<Map<String, String>> jobsPosttionSelect(List<String> codeList) {

        String inSql = "";
        for (String code : codeList) {
            inSql += "?,";
        }
        inSql = inSql.substring(0, inSql.length() - 1);
        String sql = "select code,value from SYS_DATACODE where type='titleofcadre' and flag='1'  and code IN (" + inSql + ")";
        List<Map<String, String>> resultList = sqlDao.queryForList("bd", sql, codeList.toArray());
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList;
        } else {
            return new ArrayList<>();
        }
    }


    /**
     * ====================================
     * 根据单据类型获取分摊方式
     *
     * @param bbd_id 单据类型主键
     * @return
     */
    public String getCostTypeByBBD(String bbd_id) throws Exception {
        String bbd_cost_type = "NO";
        String cache_bbd_cost_type = PubConvert.ToString(hashCache.get("bbd_cost_type_" + bbd_id));
        if (StringUtils.isNotEmpty(cache_bbd_cost_type)) {
            return cache_bbd_cost_type;
        }
        if (StringUtils.isNotEmpty(bbd_id)) {
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("business_type_id", bbd_id);
            Map<String, String> map = tableDao.queryForMap("bd", "BD_ARAP_BUSINESS_TYPE", valMap, "bx_def19");
            if (MapUtils.isNotEmpty(map)) {
                bbd_cost_type = map.get("bx_def19");
                hashCache.put("bbd_cost_type_" + bbd_id, bbd_cost_type);
            }
        }
        return bbd_cost_type;
    }


    /**
     * 查询业务类型编码是否允许附件提交修改
     *
     * @param link_order_type
     * @return
     * @throws Exception
     */
    public String getIsSubmitEditfile(String link_order_type) throws Exception {
        String is_submit_editfile = "0";
        String cache_is_submit_editfile = PubConvert.ToString(hashCache.get("is_submit_editfile_" + link_order_type));
        if (StringUtils.isNotEmpty(cache_is_submit_editfile)) {
            return cache_is_submit_editfile;
        }
        if (StringUtils.isNotEmpty(link_order_type)) {
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("business_type_id", link_order_type);
            Map<String, String> map = tableDao.queryForMap("db", "BD_ARAP_BUSINESS_TYPE", valMap, "is_submit_editfile");
            if (MapUtils.isNotEmpty(map)) {
                is_submit_editfile = map.get("is_submit_editfile");
                hashCache.put("is_submit_editfile_" + link_order_type, is_submit_editfile);
            }
        }
        return is_submit_editfile;
    }

    /**
     * 获取当前用户对应的
     * 1.人员名称
     * 2.技术职称
     *
     * @param user_id
     * @return
     * @throws Exception
     */
    public Map<String, String> getPersionNameAndTeach(String user_id) throws Exception {
        Map<String, String> map = new HashMap<>();
        String cache_persion_name_Teach = PubConvert.ToString(hashCache.get("persion_name_Teach" + user_id));
        if (StringUtils.isNotEmpty(cache_persion_name_Teach)) {
            return JsonMap.formatToMap(cache_persion_name_Teach);
        }
        if (StringUtils.isNotEmpty(user_id)) {
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("bhe_id", user_id);
            //map = tableDao.queryForMap("bd", "bd_hr_empinfo", valMap, "persion_name,persion_teach_title");

            map = sqlDao.queryForMap("bd", "SELECT persion_name,persion_teach_title FROM bd_hr_empinfo WHERE bhe_id= ?", user_id);

            if (MapUtils.isNotEmpty(map)) {
                hashCache.put("persion_name_Teach" + user_id, JSONObject.toJSONString(map));
            }
        }
        return map;
    }

    /**
     * @param persion_teach_title
     * @return
     * @throws Exception
     */
    public String getSysDataCodeTechnical(String persion_teach_title) throws Exception {
        String technical = "";
        String cache_technical = PubConvert.ToString(hashCache.get("technical_" + persion_teach_title));
        if (StringUtils.isNotEmpty(cache_technical)) {
            return cache_technical;
        }
        if (StringUtils.isNotEmpty(persion_teach_title)) {
            Map<String, Object> valMap = new HashMap<>();
            valMap.put("code", persion_teach_title);
            List<Map<String, Object>> list = (List<Map<String, Object>>) configDao.executeConfig("queryTeachByCode", valMap);
            if (CollectionUtils.isNotEmpty(list)) {
                technical = PubConvert.ToString(list.get(0).get("value"));
                hashCache.put("technical_" + persion_teach_title, technical);
            }
        }
        return technical;
    }


    //    //查询当前登陆人的人员信息
    public Map<String, String> getEmpInfo() {
        Map<String, String> empInfo = new HashMap<>();
        String user_id = CurrentUser.getUserID();
        //查询用户信息
        Map<String, String> userMap = (Map<String, String>) hashCache.get(CurrentUser.getUserID() + "userInfo");
        if (userMap == null || userMap.size() <= 0) {
            userMap = super.sqlDao.queryForMap("sf", "select user_emp_id,user_name from sys_user where user_id =?", user_id);
        }
        if (userMap == null || userMap.size() < 0) {
            return empInfo;
        } else {
            hashCache.put(CurrentUser.getUserID() + "userInfo", userMap);
        }
        String user_emp_id = PubConvert.ToString(userMap.get("user_emp_id"));
        if (StringHelp.IsNullOrEmpty(user_emp_id)) {
            String userName = PubConvert.ToString(userMap.get("user_name"));
            log.info("当前用户[" + userName + "]未配置人员信息!");
            return empInfo;
        }

        empInfo = (Map<String, String>) hashCache.get(user_emp_id + "empInfo");
        if (empInfo == null || empInfo.size() <= 0) {
            //获取当前用户对应的人员信息
            String sql = "select bhe_id,persion_code,persion_name,jobs_wagesnum,jobs_in_dept,persion_moddle_num,persion_gender,jobs_stratic_level,jobs_title_classfic \n" +
                    "from BD_HR_EMPINFO WHERE bhe_id =?";

            empInfo = super.sqlDao.queryForMap("bd", sql, user_emp_id);
            if (empInfo != null && empInfo.size() > 0) {
                hashCache.put(user_emp_id + "empInfo", empInfo);
            }
        }
        return empInfo;
    }

    /**
     * 查询报销代理人
     *
     * @param bhe_id
     * @return
     * @throws Exception
     */
    public String getAgentIDListStr(String bhe_id, String user_id) throws Exception {
        String emp_ids = bhe_id + "," + user_id;
        Map<String, Object> valMap = new HashMap<>();
        valMap.put("bas_agented_id", bhe_id);
        valMap.put("company_id", CurrentUser.getUserCurrenCompanyID());
        List<Map<String, Object>> agetIDs = (List<Map<String, Object>>) configDao.executeConfig("queryBXAgentIdAndNameByBasid", valMap);
        if (CollectionUtils.isEmpty(agetIDs)) {
            return emp_ids;
        }
        for (int i = 0; i < agetIDs.size(); i++) {
            emp_ids = emp_ids + "," + agetIDs.get(i);
        }
        return emp_ids;
    }

    /**
     * 获取代理人列表
     *
     * @param empIds
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> getAgentList(String empIds) throws Exception {
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (StringUtils.isEmpty(empIds)) {
            return mapList;
        }
        Map<String, Object> valMap = new HashMap<>();
        valMap.put("emp_ids", empIds);
        mapList = (List<Map<String, Object>>) configDao.executeConfig("queryEmpInfoListByIds", valMap);
        return mapList;
    }


    /**
     * 查询同行人数量
     *
     * @param bbId
     * @return
     */
    public Map<String, String> queryPartnerCount(String bbId) {
        if (StringUtils.isBlank(bbId)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("partner_bx_id", bbId);
        List<Map<String, String>> resultList = (List<Map<String, String>>) configDao.executeConfig("queryPartnerCount", map);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList.get(0);
        } else {
            return new HashMap<>();
        }
    }

    /**
     * 根据组织和参数编码查询参数值
     *
     * @param companyId
     * @return
     */
    public Map<String, String> queryValueByComAndCode(String companyId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("company_id", companyId);
        map.put("param_code", "BX01");
        List<Map<String, String>> resultList = (List<Map<String, String>>) configDao.executeConfigWithConditions("queryValueByComAndCode", map, null, "param_property_value", 0, 0);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList.get(0);
        } else {
            return new HashMap<>();
        }
    }

    /**
     * 查询费用明细下拉信息
     *
     * @param companyId
     * @param bbdId
     * @return
     */
    public List<Map<String, String>> queryCostDetailForSecect(String companyId, String bbdId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bbd_id", bbdId);
        map.put("company_id", companyId);
        List<Map<String, String>> resultList = (List<Map<String, String>>) configDao.executeConfig("queryCostDetailForSecect", map);
        if (CollectionUtils.isNotEmpty(resultList)) {
            return resultList;
        } else {
            return new ArrayList<>();
        }
    }
}
